using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Text;

using Kenly.DBFramework.Reflection;

namespace Kenly.DBFramework.Gateway
{
    public class EntityCollection<T> : IEnumerable<T>
    {
        private T _entity;
        private T[] _entities;

        public T FirstEntity
        {
            get
            {
                if (_entities.Length > 0)
                {
                    _entity = _entities[0];
                }
                else
                {
                    _entity=ObjectBuilder.CreateInstance<T>();
                }
                return _entity;
            }
        }

        public T[] Entities
        {
            get
            {
                return _entities;
            }
        }

        public T this[int index]
        {
            get
            {
                if (this._entities.Length <= 0)
                {
                    return ObjectBuilder.CreateInstance<T>();
                }
                if (index < 0)
                {
                    index = 0;
                }
                if (index >= this._entities.Length)
                {
                    index = this._entities.Length - 1;
                }
                return this._entities[index];
            }
        }


        public int Count
        {
            get
            {
                if (this._entities == null)
                {
                    return 0;
                }
                return this._entities.Length;
            }
        }

        public EntityCollection(T[] entities)
        {
            _entities = entities;
        }

        public EntityCollection(DataTable rawTable)
        {
            EntityRelationMapper<T>.AdaptTable(rawTable);
            _entities = EntityRelationMapper<T>.ToObjects(rawTable);
        }

        public DataTable ToDataTable()
        {
            return EntityRelationMapper<T>.ToTable(this._entities);
        }

        public DataTable CreateEmptyTable()
        {
            return EntityRelationMapper<T>.CreateEmptyTable();
        }

        #region IEnumerable<T> Members

        public IEnumerator<T> GetEnumerator()
        {
            foreach (T entity in this._entities)
            {
                yield return entity;
            }
        }

        #endregion

        #region IEnumerable Members

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this._entities.GetEnumerator();
        }

        #endregion

     
    }
}
